﻿using Application.Common.Interfaces;
using Application.Features.Menus.DTOs;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Common.Attributes;
using Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;

namespace Application.Features.Menus.Queries.GetAll;

/// <summary>
/// 全部查询
/// </summary>
[Description("全部查询")]
[GroupDescription("菜单管理")]
public class GetAllMenusQuery : IRequest<IEnumerable<MenuOutput>>
{
}

/// <summary>
/// 菜单列表
/// </summary>
[Description("菜单列表")]
[GroupDescription("菜单管理")]
public class GetMenusQuery : IRequest<IEnumerable<MenuOutput>>
{
}


public class GetAllMenusQueryHandler :
    IRequestHandler<GetAllMenusQuery, IEnumerable<MenuOutput>>,
    IRequestHandler<GetMenusQuery, IEnumerable<MenuOutput>>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;
    private readonly ICurrentUserService _currentUserService;

    public GetAllMenusQueryHandler(
        IApplicationDbContext context,
        IMapper mapper,
        ICurrentUserService currentUserService)
    {
        _context = context;
        _mapper = mapper;
        _currentUserService = currentUserService;
    }

    public async Task<IEnumerable<MenuOutput>> Handle(GetAllMenusQuery request, CancellationToken cancellationToken)
    {
        return await _context.Menus
            .OrderByDescending(o=>o.Meta.Rank)
            .Include(x => x.Meta)
            .AsNoTracking()
            .ProjectTo<MenuOutput>(_mapper.ConfigurationProvider)
            .ToListAsync();
    }

    public async Task<IEnumerable<MenuOutput>> Handle(GetMenusQuery request, CancellationToken cancellationToken)
    {
        return await _context.Menus
            .OrderByDescending(o => o.Meta.Rank)
            .Include(x => x.Meta)
            .AsNoTracking()
            .Where(x => x.Meta!.Hidden == false)
            .ProjectTo<MenuOutput>(_mapper.ConfigurationProvider)
            .ToListAsync();
    }
}